package com.chu.cloud.zuul.filter.pre;

import com.chu.cloud.zuul.properties.MicroserviceProxyRoute;
import com.chu.cloud.zuul.ratelimit.SmsRateLimitProperties;
import com.chu.cloud.zuul.ratelimit.sms.SmsPermits;
import com.chu.cloud.zuul.util.IpUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;

import static org.springframework.http.HttpStatus.TOO_MANY_REQUESTS;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/7/19 11:09
 * @Description:
 */
@Slf4j
public class SmsCodeRateLimitFilter extends ZuulFilter {

    @Autowired
    private MicroserviceProxyRoute microserviceProxyRoute;

    @Autowired
    private SmsRateLimitProperties rateLimitProperties;

    @Autowired
    private RouteLocator routeLocator;

    @Autowired
    private Map<String, SmsPermits> smsPermitsMap;

    private static final UrlPathHelper URL_PATH_HELPER = new UrlPathHelper();

    private final PathMatcher pathmatcher = new AntPathMatcher();


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        String shortUri = uri.replace(microserviceProxyRoute.getOpenService(), "");
        return uri.startsWith(microserviceProxyRoute.getOpenService())
                && pathmatcher.match("/member/smsCode", shortUri);

    }

    @Override
    public Object run() {
        final RequestContext context = RequestContext.getCurrentContext();
        context.getResponse().setCharacterEncoding("UTF-8");
        final HttpServletRequest request = context.getRequest();
        if (rateLimitProperties.isEnable()) {
            String ip = IpUtil.getIp(request);
            Route route = routeLocator.getMatchingRoute(URL_PATH_HELPER.getPathWithinApplication(request));
            log.info("请求Ip:{},url:{},service:{}", ip, route.getFullPath(), route.getId());
            String mobile = request.getParameter("mobile");
            Iterator<SmsPermits> iterator = smsPermitsMap.values().iterator();
            while (iterator.hasNext()){
                SmsPermits permits = iterator.next();
                if (!permits.isPermit(mobile)){
                    context.setResponseBody(permits.message());
                    context.setResponseStatusCode(TOO_MANY_REQUESTS.value());
                    context.setSendZuulResponse(false);
                    context.set("isProcess",false);
                }
            }
        }
        return null;
    }

}
